<style scoped>
    .rightPart{
        background-color: #d6d1d157;
        width: 66%;
    }
    .newsTop{
        background-color: white;
        width: 95%;
        margin-left: 3%;
        border-bottom: 1px solid #9a9797;
      display: flex;
    }
    .newsTop i{
        font-size: 38px;
    }
    .AIAskArea{
      display: flex;
      margin-left: 83%;
    }
    .AIAskArea:hover{
      background-color: #f7f5f2;
    }
    #AIconfont{
      font-size: 30px;
      margin-top: 5px;
      color: #1890ff;
      cursor: pointer;
    }
    .AllAsk{
      font-size: 15px;
      line-height: 37px;
      margin-left: 7px;
      cursor: pointer;
    }
    .badge {
      display: inline-block;
      color: white;
      padding: 5px;
      font-size: 13px;
      border-radius: 6px;
      margin-right: 10px;
      width: 30px;
      text-align: center;
      margin-top: 4px;
      margin-left: 3px;
    }
    .contentTitle{
        display: flex;
    }
    .newsBottom{
        margin-left: 3%;
        background-color: white;
        padding-bottom: 50px;
        width: 95%;
    }
    h2{
        margin: 0;
      padding-right: 30px;
    }
    .author{
        font-size: 14px;
        color: #5e5d5d;
        margin-left: 6%;
        margin-top: 10px;
      display: flex;
    }
    .author div{
      margin-left: 143px;
    }
    .content{
      font-size: 20px;
      line-height: 27px;
      color: #333;
      margin-left: 49px;
      //text-indent: 2em;
      margin-top: 18px;
      padding-right: 54px;
      margin-bottom: 18px;
    }
    .content img{
        max-width: 50%;
        height: auto;
    }
    .chat-container {
        width: 482px;
        height: 620px;
        border: 1px solid #ccc;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        padding: 10px;
        padding-bottom: 31px;
        background-color: white;
    }
    .chat-messages {
        flex: 1;
        overflow-y: auto;
    }
    .message {
        padding: 10px;
        margin-bottom: 10px;
        border-radius: 5px;
    }
    .user-message {
      justify-content: right;
      display: flex;
      margin-left: 73px;
    }
    .user-message div{
      background-color: #c8e6c9;
      padding: 10px 17px 10px 10px;
      border-radius: 15px;
    }
    .ai-message {
        max-width: 81%;
    }
    .ai-message div{
      background-color: #e1f5fe;
      border-radius: 15px;
      padding: 10px 10px 10px 17px;
    }
    .chat-input {
        display: flex;
        //margin-top: 10px;
    }
    .chat-input button {
        padding: 5px 10px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
      margin-top: 7px;
    }
    .AItitle{
        padding-left: 36%;
        font-size: 21px;
        border-bottom: 1px solid #a9a2a2;
        margin-bottom: 10px;
        padding-bottom: 5px;
    }
    .inPut{
        flex: 1;
        padding: 5px;
        margin-right: 10px;
        height: 24px;
    }
    .clearInput{
      font-size: 11px;
      margin-top: 20px;
      text-decoration: underline;
      cursor: pointer;
      color: #6e6e6e;
    }
    .jourImg{
      margin-left: 53px;
      width: 53%;
    }
</style>

<template>
<div style="display: flex">
    <div class="rightPart">
        <div class="newsTop">
            <i class="iconfont icon-fanhui" @click="backPage" id="back"></i>
          <div class="AIAskArea">
            <i class="iconfont icon-a-rengongzhineng-artificialintelligence-switch-fill" id="AIconfont"></i>
            <div class="AllAsk" @click="QuicklyAsk">一键询问</div>
          </div>
        </div>
        <div class="newsBottom">
            <div class="contentTitle">
                <span class="badge"
                      :style="{backgroundColor:journalismMessage.sentiment==='利好'?'red':'#008000c7'}"
                >{{journalismMessage.sentiment}}</span>
                <h2>{{journalismMessage.title}}</h2>
            </div>
            <div class="author">
              <div style="margin-left: 0">{{journalismMessage.stockCode}}  {{journalismMessage.stockName}}</div>
              <div>{{journalismMessage.newsType}}</div>
              <div>{{journalismMessage.originName}}</div>
              <div>{{journalismMessage.publishDate}}</div>
            </div>
            <div class="content"> {{journalismMessage.content}}</div>
            <div>
              <img class="jourImg" :src="journalismMessage.imageSrc">
            </div>
        </div>
    </div>
    <div style="background-color: #d6d1d157;">
        <div class="chat-container">
            <div class="AItitle">AI聊天助手</div>
            <div class="chat-messages">
                <div v-for="(message, index) in messages" :key="index" class="message" :class="{ 'user-message': message.isUser, 'ai-message':!message.isUser }">
                    <div>{{ message.text }}</div>
                </div>
              <div class="ai-message">
                <el-skeleton
                    style="width: 78%;display: flow-root;"
                    :rows="10"
                    v-if="messages.length%2===0"
                    animated />
              </div>
            </div>
            <div class="chat-input">
              <el-input v-model="inputMessage" type="textarea" :rows="3" class="inPut" placeholder="输入你的消息" />
                <div>
                  <button @click="sendMessage">发送</button>
                  <div class="clearInput" @click="clearInput">清空输入框</div>
                </div>
            </div>
        </div>
    </div>
</div>
</template>

<script setup>

import {defineProps, onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";
import {useCounterStore} from "@/stores/counter.js"
import {getJournalismDetail} from "@/api/request.js";
import {useRouter} from "vue-router";

const Router=useRouter();
const store = useCounterStore();
    const props = defineProps(['jourId']);
    let jourId=props.jourId;


    if(localStorage.getItem(('hasCheckedJournalism'))){
      let JournalismCheckedHistory=JSON.parse(localStorage.getItem('hasCheckedJournalism'));
      if(!JournalismCheckedHistory.includes(jourId) ) {
        JournalismCheckedHistory.push(jourId);
        localStorage.setItem('hasCheckedJournalism', JSON.stringify(JournalismCheckedHistory))
      }
    }else {
      let message=[]
      message.push(jourId)
      localStorage.setItem('hasCheckedJournalism',JSON.stringify(message))
    }

    let journalismMessage=ref({
      sentiment:'',
      title:'',
      publishDate:'',
      content:''
    });
    async function getJournalismMessage() {
      let message = await getJournalismDetail(jourId)
      switch (message.sentiment) {
          case 'positive':
              message.sentiment='利好'
              break;
          case 'neutral':
              message.sentiment='中性'
              break;
          case 'negative':
              message.sentiment='利空'
              break;
      }
      journalismMessage.value=message;
    }
    getJournalismMessage()

    // 将聊天记录滑动到底部
    function slideToTheBottom() {
      if(messages.value.length===0){return}
      const div=document.querySelector('.chat-messages')
      div.scrollTop=div.scrollHeight
    }


    const messages = ref([
        // 初始消息，可以是系统消息或欢迎消息
        { text: '欢迎使用 AI 聊天助手！', isUser: false }
    ]);
    const inputMessage = ref(null);

    const sendMessage = async () => {
      if (inputMessage.value === null) {
        ElMessage.error('请输入消息内容');
        return
      }
      slideToTheBottom()
      let user_chat = inputMessage.value
      inputMessage.value = null;
      await messages.value.push({text: user_chat, isUser: true});
      slideToTheBottom()
      try {
        const response = await axios.post('/api/chat/ask', {question: user_chat})
        let ai_response = response.data.split('\n').map(line => line.replace(/^data:/, '').trim()).join('')
        await messages.value.push({text: ai_response, isUser: false})
        slideToTheBottom()
      } catch (error) {
        console.error('Error during axios:', error);
      }
      let ChartHistory=store.JournalismAiChartHistory
      let index=-1
      for (let i = 0; i < ChartHistory.length; i++) {
        if(ChartHistory[i].jourId===jourId){
          index=i;
          ChartHistory[i].chat_history=messages.value
          break
        }
      }
      if(index===-1){
        ChartHistory.push({jourId:jourId,chat_history:messages.value})
      }
    };

    // 初始化聊天记录函数
    function InitMessages() {
      let ChartHistory=store.JournalismAiChartHistory
      for (let i = 0; i < ChartHistory.length; i++) {
        if(ChartHistory[i].jourId===jourId){
          messages.value=ChartHistory[i].chat_history
          break
        }
      }
    }

    onMounted(async () => {
      await InitMessages()
      slideToTheBottom()
    })

    function QuicklyAsk() {
      inputMessage.value=`新闻题目：${journalismMessage.value.title}\n新闻内容是：${journalismMessage.value.content}\n根据以上新闻，对相关股票的涨跌和市场情况做出分析并给出投资建议`
    }

    function clearInput() {
      inputMessage.value=null
    }

function backPage() {
  Router.back()
}

</script>